package api

import (
	"django_blog_gin/internal/dto"
	"django_blog_gin/internal/svc"
	"django_blog_gin/internal/utils"

	"github.com/gin-gonic/gin"
)

type refreshController struct {
	svcCtx *svc.ServiceContext
}

func NewRefreshController(svcCtx *svc.ServiceContext) gin.HandlerFunc {
	c := &refreshController{
		svcCtx: svcCtx,
	}
	return c.refresh
}

func (c *refreshController) refresh(ctx *gin.Context) {
	var req dto.RefreshReq
	if !utils.ValidateJsonBody(ctx, &req) {
		return
	}
	tokenMap, err := utils.ParseJwtToken(req.RefreshToken)
	if err != nil {
		utils.ResponseError(ctx, 400, err.Error())
		return
	}

	if tokenMap.Type != "refresh" {
		utils.ResponseError(ctx, 400, "token类型错误")
		return
	}

	utils.ResponseSuccess(ctx, gin.H{
		"account_token": utils.GenerateAccountToken(tokenMap.Username, tokenMap.UserId),
		"refresh_token": utils.GenerateRefreshToken(tokenMap.Username, tokenMap.UserId),
	}, "令牌刷新成功")
}
